using UnityEngine;

namespace DesignPatterns.LSP
{
    /// <summary>
    /// Component that can temporarily disable the taking damage in a Health component.
    /// </summary>
    [RequireComponent(typeof(Health))]
    public class Invulnerability : MonoBehaviour
    {
        [Header("Visuals")]
        [Tooltip("Particle effect to indicate PowerUp is active")]
        [SerializeField] private ParticleSystem m_ParticleSystem;
        private float m_Duration = 2f;
        private float m_Timer;
        private Health m_Health;

        public float Duration
        {
            get => m_Duration;
            set => m_Duration = value;
        }

        private void Awake()
        {
            m_Health = GetComponent<Health>();
            m_ParticleSystem.Stop();
        }

        private void Update()
        {
            // If invulnerability is active, count down the timer.
            if (m_Health.IsInvulnerable)
            {
                m_Timer -= Time.deltaTime;
                
                // If the timer has expired, deactivate invulnerability.
                if (m_Timer <= 0)
                {
                    m_Health.IsInvulnerable = false;
                    
                    Debug.Log("Invulnerability deactivated");
                    
                    if (m_ParticleSystem != null)
                        m_ParticleSystem.Stop();
                }
            }
        }

        public void Activate(float duration)
        {
            // Set the timer and activate invulnerability.
            m_Timer = duration;
            m_Health.IsInvulnerable = true;
            
            Debug.Log("Invulnerability activated");
            
            if (m_ParticleSystem != null)
            {
                
                m_ParticleSystem.Play();
            }
                
        }
        
    }
}